package com.hulk.dryad.admin.security.service;

import cn.hutool.core.util.ArrayUtil;
import com.hulk.dryad.common.constant.enums.RootFlag;
import com.hulk.dryad.common.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;

/**
 * @author hulk
 * @date 2019/6/22 接口权限判断工具
 */
@Slf4j
@Component("pms")
public class PermissionService {


	/**
	 * 判断是否超级管理员
	 * @return 是否管理员
	 */
	public boolean hasRoot() {
		AdminUser admin = SecurityUtils.getUser();
		if (admin == null) {
			return false;
		}
		if( RootFlag.ROOT.getValue().equalsIgnoreCase(admin.getRootFlag()) ){
			return true;
		}
		return false;
	}

	/**
	 * 判断接口是否有任意xxx，xxx权限
	 * @param permissions 权限
	 * @return {boolean}
	 */
	public boolean hasPermission(String... permissions) {
		if (ArrayUtil.isEmpty(permissions)) {
			return false;
		}
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			return false;
		}
		AdminUser admin = SecurityUtils.getUser(authentication);
		if (admin == null) {
			return false;
		}
		// root 有所有权限
		if( RootFlag.ROOT.getValue().equalsIgnoreCase(admin.getRootFlag()) ){
			return true;
		}
		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
		return authorities.stream().map(GrantedAuthority::getAuthority).filter(StringUtils::hasText)
				.anyMatch(x -> PatternMatchUtils.simpleMatch(permissions, x));
	}

}
